w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
JsonConvert.DeserializeObject throws an exception when attempting to deserialize byte[] to IEnumerable
You can't expect JsonConvert to magically create an implementation for an interface. You could use List<byte> or byte[] instead of IEnumerable<byte> if your architecture permits OR you can add a field to interface the Json serializer and hide your actual IEnumerable from it. private IEnumberable<byte> myBytes = null; [JsonProperty("BytesArray")] public string JsonBytes{ get{ return String.Join("",myBytes.Select(b=>b.ToString("X2"))); // this may need tweaking, null checks etc } set{ byte[] bytes = Convert.FromBase64String(value); myBytes = bytes; } [JsonIgnore] public IEnumerable<byte> BytesArray{ get{ return myBytes;} set{ myBytes = value;} } You could probably provide a converter to achieve the same thing but I'd say it's too much fiddling arou

Categories : C#

Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as output
Cipher.getInstance("AES") returns a cipher that uses PKCS #5 padding. This padding is added in all cases – when the plaintext is already a multiple of the block size, a whole block of padding is added. Specify your intentions explicitly in the Cipher.getInstance() call to avoid relying on defaults and potentially causing confusion: Cipher.getInstance("AES/ECB/NoPadding"); You will also see that you are using ECB mode, which is a bad choice in almost any situation.

Categories : Java

What instrument should be used instead python3? UnicodeDecodeError: 'utf-8' codec can't decode byte A in position B: invalid start byte
Don't use subprocess.getoutput(); it assumes that whatever output was produced by the command is decodable with the same encoding as sys.stdout uses. Try subprocess.check_output() instead; it returns bytes.

Categories : Python

Define an enum to be smaller than one byte / Why is this struct larger than one byte?
Bit packing 'Works for me' #include <iostream> enum MyEnum : unsigned char { i ,j, k, w }; struct MyStruct { MyEnum mEnum : 2; unsigned char val : 6; }; int main() { std::cout << sizeof(MyStruct); } prints out 1. How / what are you measuring? Edit: Live link Are you doing something like having a pointer as the next thing in the struct? In which case, you'll have 30bits of dead space as pointers must be 4 byte aligned on most 32bit systems. Edit: With your updated example, its the unions which are breaking you enum MyEnum : unsigned char { i ,j, k, w }; struct MyStruct { unsigned char mXb:3; unsigned char mYb:3; MyEnum mEnum:2; }; Has size 1. I'm not sure how unions and bit packing work together though, so I'm no more help.

Categories : C++

JAXB & UTF-8 Unmarshal exception "Invalid byte 2 of 2-byte UTF-8 sequence"
This is the problem in your test code: ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); You're using the platform default encoding to convert the string to a byte array. Don't do that. You've specified that you're going to use UTF-8, so you must do so when you create the byte array: ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); Likewise don't use ByteArrayOutputStream.toString(), which again uses the platform default encoding. Indeed, you don't need to convert the output to a string at all: ByteArrayOutputStream os = new ByteArrayOutputStream(); marshaller.marshal(c, os); byte[] xml = os.toByteArray(); jc = JAXBContext.newInstance(Candidate.class); Unmarshaller jaxb = jc.createUnmarshaller(); ByteArrayInputStream is = new ByteArrayInpu

Categories : Java

Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?
In FileInputStream, the method read() reads a single byte. From the source code: /** * Reads a byte of data from this input stream. This method blocks * if no input is yet available. * * @return the next byte of data, or <code>-1</code> if the end of the * file is reached. * @exception IOException if an I/O error occurs. */ public native int read() throws IOException; This is a native call to the OS which uses the disk to read the single byte. This is a heavy operation. With a BufferedInputStream, the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to

Categories : Java

Converting a byte array (byte[]) to String changes one special character
I suspect what you want is ISO-8859-1 which translates 0-255 to 0-255 as is. This means (byte) 92 => (char) 92 You cannot say 55 becomes 55 00 as these are not two bytes you can access individually, it is one char which will be 0055 or just 55 if you print this as hex.

Categories : Java

The third byte postion determines the length of that string. I want to then add a ":" at the end of each byte position
How about this: void updatefile(string filename) { char[] buffer = new char[17]; //string tempfile = Path.GetTempFileName(); string newfile = filename + ".9600.sdf"; //use tempfile and uncomment lines to replace the existing file. StreamWriter writer = new StreamWriter(newfile); StreamReader reader = new StreamReader(filename); while (!reader.EndOfStream) { writer.Write(buffer, 0, reader.Read(buffer, 0, 17)); writer.Write(":"); if (!reader.EndOfStream) writer.WriteLine(reader.ReadLine()); } writer.Close(); reader.Close(); //File.Copy(tempfile, filename, true); //File.Delete(tempfile); }

Categories : C#

Java byte[] to string conversion outputting byte
What you are seeing [B@1ef9f1d is the result of the method toString() that all classes inherit from the Object class, since all classes in Java extend Object. This is implemented as public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } In this case, getClass().getName() would return [B because it is an array of Bytes. This is because array objects in Java do not have a custom toString() method, they inherit Object's. If you want to print the contents of an array, try Arrays.toString(yourByteArray); For custom classes, you should always implement (override) your own custom toString() method. It is useful for logging. Note that String concatenation when used with reference types uses the toString() method implicitly to convert your o

Categories : Java

memcpy from Byte * to unsigned int Is Reversing Byte Order
What is going on here? Is this just an issue with endianness? Yes. Your computer is little endian. The 16-bit value 32768 would be represented in-memory as: 00 80 On a little endian machine. You have: 80 00 Which is the opposite, representing 128 as you're seeing.

Categories : C++

Java byte Insert value error string to byte
Your String "FF" seems to be a hex value, right? So you actually want to convert it to the byte value of 255. You can use a method like described here to convert a hex string to a byte array: Convert a string representation of a hex dump to a byte array using Java?. In your case, you could adapt that method to expect a 2-letter string and return a single byte instead of a byte array.

Categories : Java

Java code - negative byte in byte array to C#
In Java, bytes are signed, and in C#, bytes are unsigned. You can convert from signed to unsigned by adding 256 to the number, so that (in your example) -32 becomes 224 and -3 becomes 253. As Ichabod Clay says (in comments), you can also use the sbyte type so that you don't have to do that conversion. Personally I dislike signed bytes, so if this were for literal data, I'd just convert once and be done, but you have a choice. Yay. :-D

Categories : C#

difference between Byte constructor and Byte.valueOf() method
The documentation for the valueOf() method addresses this: If a new Byte instance is not required, this method should generally be used in preference to the constructor Byte(byte), as this method is likely to yield significantly better space and time performance since all byte values are cached.

Categories : Java

byte[] encodeBase64(byte[] binaryData) equvalent in c#
You can leverage the Convert.ToBase64String method. This will however not return a byte[] but a string type. To get it in bytes, you will have to perform a text encoding. string base64 = Convert.ToBase64String(binaryData); byte[] base64bytes = System.Text.Encoding.ASCII.GetBytes(base64);

Categories : C#

JRException: Invalid byte 1 of 1-byte UTF-8 sequence
The fact that you have <?xml version="1.0" encoding="UTF-8"?> at the beginning of your file doesn't mean that the file is actually stored in UTF-8 encoding, that just means "I swear this file has this encoding". Do you have in your file characters other than the classic ASCII? (something like the Spanish N with a tilde on it?) Try opening your file with a decent editor and save it again, choosing explicitly the encoding as UTF-8 AND after that have a look at your special characters inside your file to see if they are still the same.

Categories : Java

append single byte to byte array in vb.net
Try this Dim byte1 As Byte = &H4 Dim byte2 As Byte = &HA Dim array() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text & Chr(byte1) & Chr(byte2))

Categories : Vb.Net

Remove null byte every X byte c++ WINAPI
It seems that you don't want to use any of the more powerful features of C++ so I suspect that you are really looking for a C style routine. That would look like this: void copyskip(void *dest, const void *src, size_t srclen, size_t skip) { size_t destidx = 0; for (size_t srcidx=0; srcidx<srclen; ) { if ((srcidx+1) % skip != 0) { ((char*)dest)[destidx] = ((char*)src)[srcidx]; destidx++; } srcidx++; } } You'd need to allocate the destination buffer before calling. And for your example you would pass 3 for the skip parameter. Personally I'd much rather do it using C++ standard containers, but this is what I think you asked for.

Categories : C++

String to byte[] and byte[] to Image in .NET
Though I don't have experience with the particular library you're using, I can see some obvious problems with your code and expect them to be causing the issue. Check these two lines of your code: string sr = ""; byte[] src = new byte[sr.Length*sizeof(char)]; sr is an empty string at this time, so sr.Length will be zeroand the byte array will also be zero-length, therefore BlockCopy will not be able to write anything to it. You should move this second line inside the if block, after the line sr = textFIR.TextFIR;.

Categories : C#

List to single byte[]
I would loop the list and sum up the lengths of the arrays in the list. Create a byte[] that holds them all. Loop and copy with System.arrayCopy() into the appropriate indexes. I don't think a 3rd party library is warranted for just such a thing as what you describe. You seem to know how to code it, so I'll leave out example code.

Categories : Java

Append part of byte to another byte
You will need to left-shift the UpperLogicalLocation bits by 8 before combining the bits: int UpperLogicalLocation = 0x51; int UnderLogicalLocation = 0x23; int LogicalLocation = (UpperLogicalLocation & 0x0F) << 8; // Take bit 0-3 and shift LogicalLocation |= UnderLogicalLocation; Console.WriteLine(LogicalLocation.ToString("x")); Note that I also changed += to |= to better express what is happening.

Categories : C#

how to read byte by byte from a file
It is a single error: Invalid conversion from unsigned charto void* initializing argument 1 of size_t fread(void*,size_t,size_t,FILE*) It means k[i] is an unsigned char, and not a pointer. You should use &k[i] or k+i. However, you don't really need to read byte by byte. You can read 4 bytes, no loops involved: fread(k, 4, 1, myfile); Printing the numbers: for (i=0; i<4; i++) printf("%d ", k[i]);

Categories : C

C# - Convert unsafe byte* to byte[]
If ptr is your unsafe pointer, and the array has length len, you can use Marshal.Copy like this: byte[] arr = new byte[len]; Marshal.Copy((IntPtr)ptr, arr, 0, len); But I do wonder how you came by an unsafe pointer to native memory. Do you really need unsafe here, or can you solve the problem by using IntPtr instead of an unsafe pointer? And if so then there's probably no need for unsafe code at all.

Categories : C#

Byte vs Byte Array in Memory
When you create an array of n bytes or n byte variables the compiler has different degrees of freedom to optimize. The array has a fixed memory layout since an array is a dense data structure with no padding between the values. If you declare byte values on the other hand the JITer tries to align them on 4 or 8 byte boundaries (x64) to ensure aligned memory access. The effects of aligned vs non-aligned memory access can be around 30% for read access. This is a worthwile optimization. The holes between the bytes in this case is a non issue since less space will not make you faster. Correct memory alignment is the key to best performance.

Categories : C#

Converting issue Byte to Byte
Convert.ToByte returns a single byte, not an array. You are also using ToString which can completely convert the binary data into a representation that you can't use: MediaData = Convert.ToByte(dr["MediaData"].ToString()) Should be: MediaData = (byte[])dr.Items["MediaData"];

Categories : Asp Net

C++ Storage Copy Byte by Byte?
C++ models all of program memory as an array of bytes (characters, unsigned characters). We are legally allowed to inspect the representation of any object byte-by-byte by casting a pointer to that object into an (usually unsigned) char*. What this code is doing, is using an array of bytes as a sort-of type-independent storage space. When you call add, it copies the byte representation of the object to be added into its internal array of bytes storage. This is how one might implement a type-independent container in C, but completely inappropriate to C++, even in 2000.

Categories : C++

How to add each byte of an 8-byte long integer?
I'm not an assembly guru but this code should be a little bit faster on platforms that don't have fancy SIMD instructions: #include <stdint.h> int bytesum(uint64_t pw) { uint64_t a, b, mask; mask = 0x00ff00ff00ff00ffLLU; a = (pw >> 8) & mask; b = pw & mask; pw = a + b; mask = 0x0000ffff0000ffffLLU; a = (pw >> 16) & mask; b = pw & mask; pw = a + b; return (pw >> 32) + (pw & 0xffffffffLLU); } The idea is that you first add every other byte, then every other word, and finally every other doubleworld.

Categories : C

Byte array with padding of null bytes at the end: how to efficiently copy to smaller byte array
why not try the static method array copy in the system class just give the source array src start position , destination array , destination start position and the length System.arraycopy(src, srcPos, dest, destPos, length); byte [] dest= new byte [6000]; System.arraycopy(src, 0, dest, 0, 6000);

Categories : Java

Network stream stuck on stream.Read(byte[] byte, int offset, int size)
Because it's a stream, and can be partial received. Are you sure you are always receiving packages with te size of 2048 bytes? int i = 0; int bytesNeeded = 200; int bytesReceived = 0; do { //read byte from client int bytesRead = stream.Read(receivedBytesRaw, bytesReceived, bytesNeeded-bytesReceived); bytesReceived += bytesRead; // merge byte array to another byte array } while (bytesReceived < bytesNeeded); I think you need a frame protocol, try create a protocol like, writing the size of the data that follows. example: (psuedo) void SendData(byte[] data) { // get the 4 bytes of a int value. byte[] dataLength = BitConverter.GetBytes(data.Lenght); // write the length to the stream. stream.Write(dataLengt

Categories : C#

Convert byte array -> string -> byte array corrupts data
The array of bytes does not encode a valid text string in UTF-8, so when you "serialize" it the parts that can't be recognized are replaced by a "replacement character." If you must convert byte arrays into strings you should find an encoding that does not have restrictions like this, such as ISO-8859-1. In particular, the byte 177 cannot appear on its own in valid UTF-8: bytes in range 128 - 191 are "continuation bytes" that can appear only after a byte in range 194-244 has been seen. You can read more about UTF-8 here: https://en.wikipedia.org/wiki/UTF-8

Categories : Dotnet

Efficient Replacement of Double-Byte Numerals to Single-Byte Numerals
This is really just a transliteration problem; and what you're replacing, and what you're replacing it with, is all contiguous. So this will work: function replaceFullWidthNumerals(s) { return s.replace( /[uFF10-uFF19]/g, function(m){ return String.fromCharCode( m.charCodeAt() - 0xFEE0 ); } ); } I was inspired to write a blog post about it, too.

Categories : Regex

C# convert object[ ] into byte[ ], but how to keep byte object as byte?
There is no BitConverter.GetBytes overload that takes a byte, so your code: BitConverter.GetBytes((byte) o) Is being implicitly expanded into the nearest match: BitConverter.GetBytes(short) (Int16), resulting in two bytes. All you need to do is return a single-element byte array, e.g. like this: { typeof(byte), o => new[] { (byte) o } }

Categories : C#

Convert 1D byte image array to 2D byte array in java
Instead of using ByteArrayOutputStream use DataBufferByte,it will work. DataBufferByte db = (DataBufferByte)image.getRaster().getDataBuffer(); byte[] pixelarray = db.getData(); and then apply the logic to convert the 1D array to 2D array This gives the correct image size and avoid exception.

Categories : Java

How to convert 1D byte array to 2D byte array which holds a bitmap?
Here's a simple function that takes a 1d int array and the size of each row you want the data split up into and returns a 2d array. public int[,] ConvertArray(int[] Input, int size) { int[,] Output = new int[(int)(Input.Length/size),size]; System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:OutFile.txt"); for (int i = 0; i < Input.Length; i += size) { for (int j = 0; j < size; j++) { Output[(int)(i / size), j] = Input[i + j]; sw.Write(Input[i + j]); } sw.WriteLine(""); } sw.Close(); return Output; } I didn't add any validation to make sure the input array is exactly divisible by the size, if necessary you'll need to add that. I

Categories : C#

Converting a NV12 (YUV4:2:0) Byte array to RGB byte Array
this is best done in C++ - you can use Microsoft's DirectXTex library for it (if you want tested code). You can also convert it yourself using formulas below: CLIP(X) ( (X) > 255 ? 255 : (X) < 0 ? 0 : X) // YCbCr -> RGB CYCbCr2R(Y, Cb, Cr) CLIP( Y + ( 91881 * Cr >> 16 ) - 179 ) CYCbCr2G(Y, Cb, Cr) CLIP( Y - (( 22544 * Cb + 46793 * Cr ) >> 16) + 135) CYCbCr2B(Y, Cb, Cr) CLIP( Y + (116129 * Cb >> 16 ) - 226 ) Note that you will need dimensions of the image, not just byte size. Y channel in NV12 is located first (1 byte per pixel), then UV (2bytes per 4 pixels) as explained here: http://www.fourcc.org/yuv.php#NV12

Categories : C#

3-byte int and 5-byte long?
I think 3.9.1/2 (C++98) sums this up nicely (immediately followed by analogous information for the unsigned types): There are four signed integer types: “signed char”, “short int”, “int”, and “long int.” In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment39) ; the other signed integer types are provided to meet special needs. Basically all we know is that sizeof(char) == 1 and that each "larger" type is at least that large, with int being a "natural" size for an architecture (where as far as I can tell "natural" is up to the compiler writer). We don't know anything like CHAR_BIT * sizeof(int) <= 32 etc. Also keep in mind tha

Categories : C++

Filter out byte with certain value and XOR next byte
Well, the first thing to note is that you can't really remove a value from an array, so you can't do it in situ; so perhaps something like: static byte[] Demungify(byte[] value) { var result = new List<byte>(value.Length); bool xor = false; for (int i = 0; i < value.Length; i++) { byte b = value[i]; if (xor) { b ^= 0x20; xor = false; } if (b == 0x7D) { xor = true; // xor the following byte continue; // skip this byte } result.Add(b); } return result.ToArray(); }

Categories : C#

Joda Date-Time: Capture Date time(UTC) and convert to byte/byte array
DateTime date = new DateTime().withZone(DateTimeZone.UTC). withChronology(ISOChronology.getInstanceUTC()); If all you want is UTC you can use plain long time = System.currentTimeMillis(); BTW, all computers actually use GMT rather than supporting UTC. e.g. no leap seconds. I don't know why there is T and z there in output. ISO 8601 standard. Now I have to convert it to bytes/bytes array. There are many different ways to do this. Can you say how you need the translation to be performed? As per the standard I am following they have given an example of result after converion December 15,2005 at 17:35:19.000 ==> 07D5 0C 0F 11 23 13 0000Hex Which standard you referring to? If 07D5 0C 0F 11 23 13 0000 was the time in milli-seconds you would be in t

Categories : Java

Getting the CRC checksum of a byte array and adding it to that byte array
Use the following code instead: // Compute the MODBUS RTU CRC private static int ModRTU_CRC(byte[] buf, int len) { int crc = 0xFFFF; for (int pos = 0; pos < len; pos++) { crc ^= (int)buf[pos] & 0xFF; // XOR byte into least sig. byte of crc for (int i = 8; i != 0; i--) { // Loop over each bit if ((crc & 0x0001) != 0) { // If the LSB is set crc >>= 1; // Shift right and XOR 0xA001 crc ^= 0xA001; } else // Else LSB is not set crc >>= 1; // Just shift right } } // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes) return crc; } You may have to reverse your return CRC to get the right endianness,

Categories : Java

Type Conversion: Byte[] to String, String to Byte[]
If you really need to convert a byte[] into a String, use an intermediate serialization meant for arbitrary byte data, such Base64. Strings are for character data, not arbitrary byte[]s. Android's Base64 class makes the above trivial. This question is pretty much a duplicate of Android: using Base64 to encode an Image to String.

Categories : Java

Convert PNG byte array to JPEG byte array
Below is a snippet of code to take a byte array of any format and convert it to a byte array with a JPG format: byte[] jpgImageBytes = null; using (var origImageStream = new MemoryStream(image)) using (var jpgImageStream = new MemoryStream()) { var jpgImage = System.Drawing.Image.FromStream(origImageStream); jpgImage.Save(jpgImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); jpgImageBytes = jpgImageStream.ToArray(); jpgImage.Dispose(); }

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.